<template>
  <el-dialog
    title="角色权限设置"
    v-model="visible"
    :width="900"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <el-button type="primary" @click="expandAllClick()">{{
      menu.expandAllText
    }}</el-button>

    <div class="treeMain">
      <el-tree
        ref="menu"
        node-key="name"
        :data="menu.list"
        :default-checked-keys="menu.checked"
        :props="menu.props"
        :default-expand-all="expandAll"
        @check="nodeCheck"
        show-checkbox
      ></el-tree>
    </div>
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="isSaveing" @click="submit()"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>

<script>
export default {
  emits: ["success", "closed"],
  data() {
    return {
      roleId: 0,
      visible: false,
      isSaveing: false,
      menu: {
        list: [],
        checked: [],
        props: {
          label: (data) => {
            return data.title;
          },
        },
        expandAll: true,
        expandAllText: "收起所有",
      },
    };
  },
  mounted() {},
  methods: {
    expandAllClick() {
      this.menu.expandAll = !this.menu.expandAll;
      this.menu.expandAllText = this.menu.expandAll ? "收起所有" : "展开所有";

      for (let i = 0; i < this.$refs.menu.store._getAllNodes().length; i++) {
        this.$refs.menu.store._getAllNodes()[i].expanded = this.menu.expandAll;
      }
    },
    open(roleId) {
      this.visible = true;
      this.roleId = roleId;
      this.getMenu();
    },
    nodeCheck(node, check) {
      console.log(node, check);
      this.menu.checked = check.checkedKeys;
    },
    async submit() {
      this.isSaveing = true;
      var res = await this.$API.system.role.psave.post({
        role_id: this.roleId,
        checked: this.menu.checked,
      });

      if (res.code == 200) {
        this.$emit("success", this.form, this.mode);
        this.visible = false;
        this.$message.success("操作成功");
      } else {
        this.$alert(res.message, "提示", { type: "error" });
      }

      this.isSaveing = false;
      this.visible = false;

      return false;
    },
    async getMenu() {
      var res = await this.$API.system.role.permission.get({
        role_id: this.roleId,
      });
      this.menu.list = res.data.list;
      this.menu.checked = res.data.permission;
    },
  },
};
</script>

<style scoped>
.treeMain {
  /* height: 280px; */
  overflow: auto;
  border: 1px solid #dcdfe6;
  margin-bottom: 10px;
}
</style>
